package yace;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类
 * 
 * @author Liuxey
 *
 */
public class HttpRequestUtils {

	public static final String REQUEST_TYPE_GET = "get";
	public static final String REQUEST_TYPE_POST = "post";
	public static final String REQUEST_ENCODING = "utf-8";
	private static Log log = LogFactory.getLog(HttpRequestUtils.class);
	
	/**
	 * 模拟发出Http请求
	 * 
	 * @param uri 请求资源,如：http://www.baidu.com/,注意严谨的格式
	 * @param params 请求参数
	 * @param type 请求方式,目前只支持get/post
	 * @param encoding 网页编码
	 * 
	 * @return HttpResponseBody
	 * 
	 * @throws java.io.IOException
	 * @throws org.apache.http.client.ClientProtocolException
	 */
	public static String request(String uri, Map<String,String> params, String type, String encoding) throws ClientProtocolException, IOException{
		String result = "";
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpResponse httpResponse = null;

		// GET方式请求
		if(HttpRequestUtils.REQUEST_TYPE_GET.equals(type)){
			// 加入请求参数
			if(params != null ){
				if(uri.indexOf("?") != -1){
					uri += "&";
				}else{
					uri += "?";
				}
				for(String key : params.keySet()){
					uri += key +"="+params.get(key) +"&";
				}
			}
			HttpGet httpGet = new HttpGet(uri);
			httpResponse = httpClient.execute(httpGet);

		// POST方式请求
		}else if(HttpRequestUtils.REQUEST_TYPE_POST.equals(type)){
			HttpPost httpPost = new HttpPost(uri);
			// 加入请求参数
			if(params != null ){
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for(String key : params.keySet()){
					if(key != null){
						paramList.add(new BasicNameValuePair(key, params.get(key)));
					}
				}
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"UTF-8");
				httpPost.setEntity(entity);
			}
			httpResponse = httpClient.execute(httpPost);
		}

		// 获取返回内容
		HttpEntity entity = httpResponse.getEntity();
		if(entity!=null){

			BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
			String s = "";
			while ((s = br.readLine()) != null) {
				result += s;
			}
			if(br != null) {
				br.close();
			}
		}
		return result;
	}





	/**
	 * 模拟发出Http请求
	 *
	 * @param uri 请求资源,如：http://www.baidu.com/,注意严谨的格式
	 * @param params 请求参数
	 * @param type 请求方式,目前只支持get/post
	 * @param encoding 网页编码
	 *
	 * @return HttpResponseBody
	 *
	 * @throws java.io.IOException
	 * @throws org.apache.http.client.ClientProtocolException
	 */
	public static String requestObject(String uri, Map<String,Object> params, String type, String encoding) throws ClientProtocolException, IOException{
		String result = "";
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpResponse httpResponse = null;
		
		// GET方式请求
		if(HttpRequestUtils.REQUEST_TYPE_GET.equals(type)){
			// 加入请求参数
			if(params != null ){
				if(uri.indexOf("?") != -1){
					uri += "&";
				}else{
					uri += "?";
				}
				for(String key : params.keySet()){
					uri += key +"="+params.get(key) +"&";
				}
			}
			HttpGet httpGet = new HttpGet(uri);
			httpResponse = httpClient.execute(httpGet);
			
		// POST方式请求
		}else if(HttpRequestUtils.REQUEST_TYPE_POST.equals(type)){
			HttpPost httpPost = new HttpPost(uri);
			// 加入请求参数
			if(params != null ){
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for(String key : params.keySet()){
					if(key != null){
						paramList.add(new BasicNameValuePair(key, params.get(key)+""));
					}
				}
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"UTF-8");
				httpPost.setEntity(entity);
			}
			httpResponse = httpClient.execute(httpPost);
		}
		
		// 获取返回内容
		HttpEntity entity = httpResponse.getEntity();
		if(entity!=null){
			
			BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
			String s = "";
			while ((s = br.readLine()) != null) {  
				result += s;
			}
			if(br != null) {
				br.close();  
			}
		}
		return result;
	}
	
	
	
	
	
	
	
	/**
	 * 上传图片至公共服务器
	 * 
	 * @param url
	 * @param filePath
	 * @param folderId
	 * @param busyId
	 * @param userId
	 * @param imageName
	 * @param sourceId
	 * @param imageDesc
	 * @param encoding
	 * @return
	 */
	public static String uploadImage(String url, String filePath, String folderId, String busyId, String userId, String imageName, String sourceId, String imageDesc, String encoding) {
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			
			
			// 文件
			FileBody file = new FileBody(new File(filePath));
			// 文本
			StringBody folderIdBody = new StringBody(folderId, Charset.forName(encoding));
			StringBody busyIdBody = new StringBody(busyId, Charset.forName(encoding));
			StringBody userIdBody = new StringBody(userId, Charset.forName(encoding));
			StringBody imageNameBody = new StringBody(imageName, Charset.forName(encoding));
			StringBody sourceIdBody = new StringBody(sourceId, Charset.forName(encoding));
			StringBody imageDescBody = new StringBody(imageDesc, Charset.forName(encoding));
			
			// 请求实体
			MultipartEntity reqEntity = new MultipartEntity();
			
			// 把请求参数加入请求实体中,包含文件和字符串
			reqEntity.addPart("file", file);
			reqEntity.addPart("folderId", folderIdBody);
			reqEntity.addPart("busyId", busyIdBody);
			reqEntity.addPart("userId", userIdBody);
			reqEntity.addPart("imageName", imageNameBody);
			reqEntity.addPart("sourceId",sourceIdBody);
			reqEntity.addPart("imageDesc",imageDescBody);
			
			// 设置请求实体
			httppost.setEntity(reqEntity);
			
			// 请求
			log.info("请求头: " + httppost.getRequestLine());
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity resEntity = response.getEntity();
			log.info("状态行：" + response.getStatusLine());
			
			if(resEntity!=null){
				InputStream is = resEntity.getContent();
				int l ;
				byte[] buff = new byte[9192];
				while( (l = is.read(buff)) != -1){
					result += new String(buff, 0, l, encoding);
				}
			}
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}
	
	/**
	 * 直接调用get方法，获取url返回内容
	 * 
	 * @param url get请求的地址,带http完整格式
	 * @param encoding 网页编码
	 */
	public static String get(String url, String encoding){
		String result = "";
		try {
			result = HttpRequestUtils.request(url, null, HttpRequestUtils.REQUEST_TYPE_GET, encoding);
		} catch (Exception e) {
			result = e.getMessage();
		}
		return result;
	}
	
	/**
	 * 调用post请求url地址
	 * 
	 * @param url 请求地址,带http完整格式
	 * @param params 请求参数
	 * @param encoding 网页编码
	 * @return
	 */
	public static String post(String url, Map<String, String> params, String encoding){
		String result = "";
		try {
			result = HttpRequestUtils.request(url, params, HttpRequestUtils.REQUEST_TYPE_POST, encoding);
		//	result = HttpRequestUtils.requestUri(url, params, HttpRequestUtils.REQUEST_TYPE_POST, encoding);
		} catch (Exception e) {
			result = e.getMessage();
		}
		return result;
	}
}
